<template>
  <view class="page">

    <!-- 顶部地图 -->
    <map
      id="map"
      :class="['map', isFull ? 'map-full' : '']"
      :latitude="center.latitude"
      :longitude="center.longitude"
      :scale="16"
      :markers="markers"
      show-location="true"
      @markertap="onMarkerTap"
    >
      <!-- 居中锚点（可选） -->
      <cover-view class="center-pin">
        <cover-image src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/location.png?1" class="pin-icon" />
      </cover-view>

      <!-- 右上角：全屏/退出、回到定位（必须用 cover-view） -->
      <cover-view class="map-tools">
        <cover-view class="tool-btn" @tap="toggleFull">{{ isFull ? '退出全屏' : '全屏地图' }}</cover-view>
      </cover-view>
    </map>

    <!-- 下半区：操作与列表（全屏时隐藏） -->
    <view class="panel" v-show="!isFull">

      <!-- 渐变扫码租赁按钮 -->
      <view class="cta" @tap="scanToRent">
        <text class="iconfont icon-saoma"></text>
        <text class="cta-text" v-if="can_back == 0">扫码租车</text>
		<text class="cta-text" v-else>扫码还车</text>
      </view>

      <!-- 附近站点 -->
      <view class="sec-title">
        <view class="bar"></view>
        <text>附近站点</text>
        <view class="more" @tap="seeMore">查看更多 ></view>
      </view>
      
      <!-- 列表（用普通 view，不再单独滚动） -->
      <view class="list">
        <view
          class="station-card"
          v-for="(s, idx) in stations"
          :key="s.id"
          @tap="focusStation(idx)"
        >
          <view class="left">
            <view class="poi-title-row">
              <image class="poi-icon" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/dingwei.png?1" mode="widthFix" />
              <text class="poi-title">{{ s.name }}</text>
            </view>
            <view class="poi-sub">{{ s.addr }}</view>
            <view class="poi-status">
              <view class="dot usable"></view><text>可用:{{ s.usable }}</text>
              <view class="dot idle"></view><text>可还:{{ s.returnable }}</text>
            </view>
          </view>
          <view class="right">
            <view class="dist">距离{{ s.distanceText }}</view>
            <image 
              class="nav-btn-img" 
              src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/daohang2.png" 
              mode="widthFix"
              @tap.stop="navTo(idx)" 
            />
          </view>
        </view>
      </view>

    <!-- 学习骑行规则（3宫格） -->
    <view class="rules">
      <view class="rule-item" @tap="param_to_url('news_details?title=用车规则')">
        <image class="ri-ico" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/guize.png" mode="widthFix" />
        <text class="ri-txt">用车规则</text>
      </view>
      <view class="rule-item" @tap="param_to_url('news_details?title=安全行驶')">
        <image class="ri-ico" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/anquan.png" mode="widthFix" />
        <text class="ri-txt">安全行驶</text>
      </view>
      <view class="rule-item" @tap="param_to_url('news_details?title=计费规则')">
        <image class="ri-ico" src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/jifei.png" mode="widthFix" />
        <text class="ri-txt">计费规则</text>
      </view>
    </view>


      <!-- 底部Logo（可选） -->
      <view class="brand">
        <image src="https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/logo2.png" mode="widthFix" />
      </view>
    </view>
  </view>
</template>

<script>
import common_config from '../../static/js/common.js';
var config = common_config.config;
var that;	
var userInfo;
export default {
  data() {
    return {
      center: { latitude: 24.482, longitude: 118.094 }, // 默认中心
      markers: [],
      stations: [],
	  can_back:0,		//显示租车还是还车开关
	  rowid:'',
	  order_rowid:'',
      isFull: false ,// ✅ 新增：全屏开关
	  order_pay_rowid:'',
	  no_pay:0,		//是否存在待支付订单
	  tixing_zhifu:0,		//是否有提醒支付
	  zfjl:''
    }
  },
  onShow() {
    that = this;
	that.no_pay = 0;
    this.locate(); // 打开页自动定位到当前位置
    that.plusReady();
  },
  methods: {
    // ✅ 新增：切换全屏
    toggleFull(){
      this.isFull = !this.isFull;
      // 可选：进入全屏时略微放大
      // #ifdef MP-WEIXIN
      if (this.isFull) {
        this.$nextTick(() => {
          const ctx = wx.createMapContext('map', this);
          ctx.setZoom && ctx.setZoom({ zoom: 17 });
        });
      }
      // #endif
    },

    //初始化
    plusReady(){
      userInfo = uni.getStorageSync('userInfo');
      if(userInfo){
        userInfo = JSON.parse(userInfo);
        that.if_login = true;
        that.member_profile = userInfo;
		that.get_orders('使用中','unlock');
		that.get_orders('待支付','nopay');
      }else{
        that.if_login = false;
      }
    },
    load_datas(){
      uni.request({
        url: config.request_url+'/v2/open/worksheet/getFilterRows',
        method: 'POST',
        header: { 'Content-Type': 'application/json' },
        data: {
          "appKey": config.appKey,
          "sign": config.sign,
          "worksheetId": "padgl",
          "pageSize":10,
          "pageIndex":1
        },
        success: (res) => {
          res = res.data;
          if(res.success){
            var datas = res.data.rows;
            var arr = [];
            for(var i = 0;i < datas.length;i++){
              var r = datas[i].jingweidu;
              r = r.split(',');
              arr.push({
                id: datas[i].id,
                name: datas[i].paddwmc,
                addr: datas[i].diqu,
                latitude: r[0],
                longitude: r[1],
                usable: datas[i].kysl,
                returnable: datas[i].khsl,
                distance: 0
              });
            }
            if(arr.length > 0){
              arr = common_config.sortStationsByDistance(arr, that.center);
              that.stations = arr;
              this.initMarkers();
            }
          }else{
            uni.showToast({ title: res.data?.msg || '数据获取失败', icon: 'none' });
          }
        },
        fail: (err) => {
          console.error('请求失败:', err);
          uni.showToast({ title: '网络错误', icon: 'none' });
        }
      })  
    },
	//获取当前用户订单状态
	get_orders(st,act){
	  uni.request({
	    url: config.request_url+'/v2/open/worksheet/getFilterRows',
	    method: 'POST',
	    header: { 'Content-Type': 'application/json' },
	    data: {
	      "appKey": config.appKey,
	      "sign": config.sign,
	      "worksheetId": "ddgl",
	      "pageSize":50,
	      "pageIndex":1,
		  "filters": [
			  {
				  "controlId": "yonghu",
				  "dataType": 29,
				  "spliceType": 1,
				  "filterType": 24,
				  "value": userInfo.rowid//用户记录的rowid
			  },
			  {
				  "controlId": "ddzt",
				  "dataType": 11,
				  "spliceType": 1,
				  "filterType": 1,
				  "value": st
			  }
		  ]
	    },
	    success: (res) => {
	      res = res.data;
	      if(res.success){
	        var datas = res.data;
			if(act == 'unlock'){
				if(datas.rows.length > 0){
					that.can_back =1;
					that.order_rowid = datas.rows[0].rowid;
				}
			}
			if(act == 'nopay'){
				if(datas.rows.length > 0){
					that.no_pay = 1;
					that.order_pay_rowid = datas.rows[0].rowid;
					var r = JSON.parse(datas.rows[0].zfjl);
					that.zfjl = r[0];
					if(that.tixing_zhifu == 0){
						uni.showModal({
							title:'支付提醒',
							content:'您有一笔待支付订单需要支付，是否立即前往',
							success(res) {
								that.tixing_zhifu = 1;
								if(res.confirm){
									uni.navigateTo({
										url:'/pages/index/pay?rowid='+that.order_pay_rowid+'&zfjl='+that.zfjl
									});
								}
							}
						});
					}
				}
			}
			
	      }else{
	        uni.showToast({ title: res.data?.msg || '数据获取失败', icon: 'none' });
	      }
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	      uni.showToast({ title: '网络错误', icon: 'none' });
	    }
	  })  
	},
	//执行扫码还车
	scan_back(){
	  uni.request({
	    url: config.request_url+'/v2/open/worksheet/editRow',
	    method: 'POST',
	    header: { 'Content-Type': 'application/json' },
	    data: {
	      "appKey": config.appKey,
	      "sign": config.sign,
	      "worksheetId": "ddgl",
	      "triggerWorkflow": true,
		  "rowId":that.order_rowid,
		  "controls": [
		      {
		        "controlId": "ddzt",
		        "value": "还车中"
		      },
		      {
		        "controlId": "ghddpad",
		        "value": that.rowid // 归还地点Pad的rowid (扫归还二维码获取的)
		      }
		    ]
	    },
	    success: (res) => {
	      res = res.data;
	      if(res.success){
	        var datas = res.data;
			uni.showToast({
				title:'车辆归还中，请稍后'
			});
			that.can_back = 0;
	      }else{
	        uni.showToast({ title: res.data?.msg || '数据获取失败', icon: 'none' });
	      }
	    },
	    fail: (err) => {
	      console.error('请求失败:', err);
	      uni.showToast({ title: '网络错误', icon: 'none' });
	    }
	  })  
	},
    //分享到好友/朋友圈（保持不变）
    onShareAppMessage(res) {
      return {
        success(res){ uni.showToast({ title:'分享成功' }) },
        fail(res){ uni.showToast({ title:'分享失败', icon:'none' }) }
      }
    },
    onShareTimeline(res) {
      return {
        success(res){ uni.showToast({ title:'分享成功' }) },
        fail(res){ uni.showToast({ title:'分享失败', icon:'none' }) }
      }
    },
    initMarkers() {
      this.markers = this.stations.map(s => ({
        id: s.id,
        latitude: s.latitude,
        longitude: s.longitude,
        iconPath: 'https://kehu-1256834579.cos.ap-shanghai.myqcloud.com/weier/dingwei.png?1',
        width: 28,
        height: 28,
        callout: {
          content: s.name,
          display: 'BYCLICK',
          padding: 6,
          borderRadius: 6
        }
      }))
    },
    locate() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.center = { latitude: res.latitude, longitude: res.longitude };
          uni.setStorageSync('location_center',JSON.stringify(that.center));
          that.load_datas();
        },
        fail: () => {
          uni.showToast({ title: '定位失败', icon: 'none' });
          uni.setStorageSync('location_center',JSON.stringify(that.center));
          that.load_datas();
        }
      })
    },
    // ✅ 修正：事件要拿 e，才能取 markerId
    onMarkerTap(e) {
      const mId = e.detail.markerId;
      const s = this.stations.find(x => x.id === mId);
      if (s) this.focusStation(this.stations.indexOf(s));
    },
    focusStation(s) {
      this.center = { latitude: parseFloat(that.stations[s].latitude), longitude: parseFloat(that.stations[s].longitude) }
      uni.showToast({ title: that.stations[s].name, icon: 'none' })
    },
    navTo(s) {
      uni.openLocation({ latitude: parseFloat(that.stations[s].latitude), longitude: parseFloat(that.stations[s].longitude), name: that.stations[s].name, address: that.stations[s].addr });
    },
	param_to_url(url){
		uni.navigateTo({
			url:url
		})	  
	},
    scanToRent() {
      if(!that.if_login){
        uni.showModal({
          title:'友情提示',
          content:'请先登录后完成该操作',
          success(res) {
            if(res.confirm){
              uni.navigateTo({ url:'/pages/index/login' });
            }
          }
        })
        return;
      }
	 
      // 微信端扫码
      // #ifdef MP-WEIXIN
      wx.scanCode({
        success: (res) => {
		  const rowid = that.getQueryString(res.result,'rowid');
		  const act = that.getQueryString(res.result,'act');
		  console.log(res.result);
		  if(act == 'unlock'){
			  if(that.can_back == 1){
				  return false;
			  }
			  if(that.no_pay == 1){
				  uni.showModal({
				  	title:'支付提醒',
				  	content:'您有一笔待支付订单，请完成支付后继续用车',
				  	success(res) {
				  		if(res.confirm){
				  			uni.navigateTo({
				  				url:'/pages/index/pay?rowid='+that.order_pay_rowid+'&zfjl='+that.zfjl
				  			});
				  		}
				  	}
				  });
				  return false;
			  }
			  uni.navigateTo({ url:'/pages/index/jiesuo?rowid='+rowid });
		  }
		  if(act == 'lock' && that.can_back == 1){
			  //common_config.calert('还车');
			  that.rowid = rowid;
			  that.scan_back();
		  }
         // uni.navigateTo({ url:'/pages/index/jiesuo?rowid='+res.result });
          uni.showToast({ title: '扫码成功', icon: 'success' })
        }
      })
      // #endif
    },
	getQueryString(url, name) {
	  let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	  let query = url.split("?")[1];
	  if (!query) return null;
	  let result = query.match(reg);
	  return result ? decodeURIComponent(result[2]) : null;
	},
    seeMore() {
      uni.navigateTo({ url:'/pages/index/fujin' });
    },
    goRule(type) {
      uni.navigateTo({ url: `/pages/rule/rule?type=${type}` })
    },
    onMore() {
      uni.showActionSheet({
        itemList: ['切换地图类型', '回到当前位置'],
        success: (res) => {
          if (res.tapIndex === 0) {
            // TODO: 可扩展卫星图/3D等
          }
          if (res.tapIndex === 1) this.locate()
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page { min-height: 100vh; background: #f7f8fa;}

/* 地图默认高度 */
.map { width: 100%; height: 46vh; }

/* 全屏态：脱离文档流覆盖全屏 */
.map-full {
  position: fixed; left: 0; top: 0;
  width: 100vw; height: 100vh; z-index: 999;
}

/* 覆盖在map上的悬浮层（必须用cover-view） */
.center-pin { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -100%); }
.pin-icon { width: 52rpx; height: 73rpx; }

.map-tools {
  position: absolute; right: 24rpx;
  top: calc(24rpx + constant(safe-area-inset-top));
  top: calc(24rpx + env(safe-area-inset-top));
  display: flex; flex-direction: column; gap: 16rpx;
}
.tool-btn {
  display: flex;
  align-items: center;
  justify-content: center;

  min-width: 120rpx; /* 让按钮有个宽度，不然太窄 */
  padding: 12rpx 20rpx;
  border-radius: 999rpx;
  background: rgba(0,0,0,.6);
  color: #fff;
  font-size: 26rpx;
  box-shadow: 0 6rpx 18rpx rgba(0,0,0,.15);
}

/* 下方面板 */
.panel {
  margin-top: -24rpx;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  background: #fff;
  padding: 24rpx;
}

/* 渐变CTA */
.cta {
  height: 120rpx; border-radius: 999rpx;
  background: linear-gradient(90deg,#1aa0ff,#3fd2ff);
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-weight: 700; font-size: 36rpx;
  box-shadow: 0 12rpx 28rpx rgba(26,160,255,0.25);
  margin: 8rpx 0 24rpx;
}
.cta .iconfont{font-size: 40rpx; margin-right: 16rpx;color: #333;}
.cta-text { letter-spacing: 2rpx; color: #333;}

/* 标题行 */
.sec-title { display: flex; align-items: center; position: relative; font-weight: 600; font-size: 30rpx; margin: 8rpx 0 12rpx; }
.sec-title .bar { width: 8rpx; height: 28rpx; border-radius: 4rpx; background: #2aa9ff; margin-right: 12rpx; }
.more { position: absolute; right: 0; color: #9aa0a6; font-size: 26rpx; }

/* 列表 */
.list { margin-top: 20rpx; }   /* 删除 max-height */
.station-card { display: flex; justify-content: space-between; align-items: center; background: #F3F3F3; border-radius: 16rpx; padding: 20rpx; margin-bottom: 16rpx; }

.left { flex: 1; padding-right: 16rpx; }
.poi-title-row {display: flex;align-items: center;gap: 8rpx;}
.poi-icon {width: 28rpx;height: 28rpx;}
.poi-title {font-size: 30rpx;font-weight: 600;color: #333;}

.poi-sub { color: #8a8f98; font-size: 24rpx; margin-top: 6rpx; }
.poi-status { display: flex; align-items: center; gap: 18rpx; margin-top: 12rpx; color: #60646b; font-size: 24rpx; }
.dot { width: 12rpx; height: 12rpx; border-radius: 50%; margin-right: 6rpx; }
.usable { background: #2a9dff; }
.idle { background: #c9ccd1; }
.nav-btn-img {
  width: 120rpx;   /* 这里根据你上传图片实际比例调整 */
  height: auto;
}
.right { display: flex; flex-direction: column; align-items: flex-end; gap: 12rpx; }
.dist { color: #31343a; font-size: 26rpx; }
.nav-btn { background: #e9f5ff; color: #199fff; border-radius: 999rpx; padding: 0 20rpx; }

/* 规则区 */
.rules { display: grid; grid-template-columns: repeat(3,1fr); gap: 16rpx; margin-top: 16rpx; }
.rule-item { background: #f6f7f9; border-radius: 16rpx; padding: 24rpx 0; display: flex; flex-direction: column; align-items: center; gap: 10rpx; }
.ri-ico { width: 64rpx; height: 64rpx; }
.ri-txt { font-size: 26rpx; color: #3f444d; }

/* 品牌Logo */
.brand { display: flex; justify-content: center; padding: 24rpx 0 8rpx; margin-top: 80rpx;padding-bottom: 40rpx;}
.brand image { width: 180rpx; }
</style>
